package com.yiboshi.rehrs.controller;

import com.alibaba.fastjson.JSONObject;
import com.yiboshi.rehrs.common.VarConstant;
import com.yiboshi.rehrs.config.RehrsSystemConfig;
import com.yiboshi.rehrs.config.ThreadLocalSession;
import com.yiboshi.rehrs.domain.entity.ZhongUser;
import com.yiboshi.rehrs.domain.entity.ZhongUserImage;
import com.yiboshi.rehrs.domain.service.IZhongUserImageService;
import com.yiboshi.rehrs.domain.service.IZhongUserService;
import com.yiboshi.rehrs.feign.PosterFeign;
import com.yiboshi.rehrs.feign.PosterFeignInterceptor;
import com.yiboshi.rehrs.helper.HelperZhong;
import com.yiboshi.rehrs.helper.HttpHelper;
import com.yiboshi.rehrs.helper.RedisHelper;
import com.yiboshi.rehrs.param.ZhongReq;
import com.yiboshi.rehrs.param.smurfs.LogonReq;
import com.yiboshi.rehrs.param.smurfs.UserInfo;
import com.yiboshi.rehrs.util.AesGcmUtil;
import com.yiboshi.rehrs.util.JwtUtil;
import com.yiboshi.rehrs.util.StrUtils;
import com.yiboshi.rehrs.util.ThreadPoolUtils;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicBoolean;

@RestController
@RequestMapping("/smf/logon/")
@Slf4j
public class SmurfsLogonController {
    @Autowired
    RedisHelper redisHelper;

    @Autowired
    PosterFeign posterFeign;

    @Autowired
    HttpHelper httpHelper;

    @Autowired
    IZhongUserService zhongUserService;

    @Autowired
    IZhongUserImageService zhongUserImageService;

    @ApiOperation(value = "1.0 logon", httpMethod = "POST", notes = "1.0 发短信", consumes = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping("sendAuthCodeByUsr")
    public JSONObject sendAuthCodeByUsr(@RequestBody() LogonReq logonReq) {
        String personNo = logonReq.getPerson_no();
        String imei = logonReq.getImei();
        if(StrUtils.isBlank(imei)){
            imei = redisHelper.defaultImei();
        }
        logonReq.setImei(imei);
        Map<String, String> meger = getLogonMap( personNo,imei,"sendauthcode");
        JSONObject jsonObject = new  JSONObject();
        jsonObject.put("person_no",personNo);
        PosterFeignInterceptor.setHeader(meger);
        JSONObject res = posterFeign.sendauthCodeByUsr(jsonObject);
        return res;
        //new OkHttpUtil().retryCount(2).

    }

    private Map<String, String> getLogonMap(String personNo,String imei, String uriType) {
        HelperZhong helperZhong = redisHelper.selectHelper();
        ZhongReq zhongReq = new ZhongReq();
        zhongReq.setType(uriType);
        zhongReq.setImei(imei);
        zhongReq.setAccount(personNo);
        Map<String, String> headerMap = helperZhong.logonHeader(zhongReq);
        Map<String, String> meger = helperZhong.meger(headerMap);
        return meger;
    }

    @ApiOperation(value = "1.1 login", httpMethod = "POST", notes = "1.1 登录", consumes = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping("in")//{"msg":"登录失败：图⽚中没有⼈脸（检查图⽚质量）","resCode":"B00405"}
    public JSONObject logon(@RequestBody() LogonReq logonReq) {
        /*String tokenHistory = ThreadLocalSession.getToken();
        if(StrUtils.isNotBlank(tokenHistory)){
            //token有效直接返回可以用
        }*/
        //1人脸 2短信
        Integer type = logonReq.getType();
        JSONObject req =
                (JSONObject) JSONObject.toJSON(logonReq);
        JSONObject jsonObjectRes = null;
        req.remove("type");
        String imei = logonReq.getImei();
        if(StrUtils.isBlank(imei)){
            imei = redisHelper.defaultImei();
        }
        ZhongUser zhongUser = new ZhongUser();
        zhongUser.setImei(imei);
        zhongUser.setAccount(logonReq.getPerson_no());
        AtomicBoolean emptyImage = new AtomicBoolean(true);
        if(Objects.equals(type,2)){
            //短信登录
            //PosterFeignInterceptor.setHeader(getLogonMap(logonReq.getPerson_no(), logonReq.getImei(),"loginbyusrsms"));
            //jsonObjectRes = posterFeign.smsLogon(req);
            jsonObjectRes = httpHelper.sendPost("/pdalogin/p/common/loginbyusrsms", zhongUser, req);
        }else{
            String imageFace = logonReq.getImage_face();
            if(StrUtils.isBlank(imageFace)|| RehrsSystemConfig.isTest()){
                ZhongUserImage one = zhongUserImageService.getOne(logonReq.getPerson_no());
                if(one!=null){
                    emptyImage.set(false);
                    imageFace = one.getImage();
                }
            }
            if(StrUtils.isBlank(imageFace)){
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("msg","");
                jsonObject.put("resCode","B00405");
                return jsonObject;
            }
            req.put("image_face",imageFace+System.currentTimeMillis());
            req.remove("imei");
            req.remove("telephone");
            req.remove("auth_code");
            //短信登录
            //PosterFeignInterceptor.setHeader(getLogonMap(logonReq.getPerson_no(), logonReq.getImei(),"loginbyusrface"));
            //jsonObjectRes = posterFeign.loginByFace(req);

            jsonObjectRes = httpHelper.sendOriginPost("/pdalogin/p/common/loginbyusrface", zhongUser, req);
        }
        JSONObject obj = jsonObjectRes.getJSONObject("obj");
        if(obj==null){
            return jsonObjectRes;
        }
        JSONObject user = obj.getJSONObject("user");
        if(user==null){
            return jsonObjectRes;
        }
        String token =  Optional.ofNullable(user).map(o->o.getString("token")).orElse("");

        if(StrUtils.isBlank(token)){
            return jsonObjectRes;
        }
        String substitutionOrgListString = obj.getString("substitutionOrgList");
        String smToken = AesGcmUtil.encryptAccount(token);// JwtUtil.generateToken(token);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put(VarConstant.Authorization.toLowerCase(),smToken);
        jsonObject.put("substitutionOrgList",substitutionOrgListString);
        jsonObjectRes.put("obj",jsonObject);
        log.info("account logon success,{},token:{}",logonReq.getPerson_no(),smToken);
        ThreadPoolUtils.submitTask(()->{
            String userInfoString = obj.getString("user");
            UserInfo userInfo = JSONObject.parseObject(userInfoString, UserInfo.class);
            //userInfo.setImei(redisHelper.defaultImei());
            //userInfo.setImei();


            //入库
            zhongUser.setAccount(logonReq.getPerson_no());
            zhongUser.setAutoStatus(0);
            zhongUser.setAutoTaskType(2);
            zhongUser.setToken(token);
            //zhongUser.setImei(userInfo.getImei());
            //zhongUser.setPadId(userInfo.getImei());
            zhongUser.setFullname(userInfo.getPerson_name());
            zhongUser.setVipExpDate(LocalDateTime.now());
            zhongUser.setOrgLatitude(userInfo.getOrg_latitude());
            zhongUser.setOrgLongitude(userInfo.getOrg_longitude());
            zhongUser.setSimpleNameCn(userInfo.getSimple_name_cn());
            zhongUser.setOrgNo(userInfo.getOrg_no());
            zhongUser.setTelephone(userInfo.getTelephone());
            zhongUser.setAgentAccount("");
            ZhongUserImage zhongUserImage = null;
            if(Objects.equals(type,1)&&emptyImage.get()){
                zhongUserImage = new ZhongUserImage();
                zhongUserImage.setImage(logonReq.getImage_face());
                zhongUserImage.setAccount(logonReq.getPerson_no());
            }
            zhongUser.setMode(1);
            redisHelper.smSaveSession(zhongUser);
            zhongUserService.saveOrUpdateUserFace(zhongUser,zhongUserImage);

            //加载列表
            //redis缓存
            /*
            "substitutionOrgList": [
                    {
                        "simpleNameProduct": "昆山开发",
                        "orgname": "中国邮政集团有限公司江苏省昆山市开发区揽投部(替班失效剩余3天)",
                        "orgCode": "21530121",
                        "orgid": 11443
                    }
                ],
                "user": {
                    "token": "264b12173d114dd29310cc2a83385173",
                    "token_expire_time": 1800000,
                    "person_id": 2901143,
                    "person_no": "2153011500166",
                    "employee_id": 2721346,
                    "erp_person_no": "2153011500166",
                    "person_name": "杨猛",
                    "org_id": "22902",
                    "org_no": "21530115",
                    "org_name": "中国邮政集团有限公司江苏省昆山市开发区投揽投部",
                    "simple_name_cn": "昆山开发区投揽投部",
                    "administrative_Division": "320583",
                    "area_Code": "320583",
                    "simple_name_product": "A昆开发",
                    "drds_org_code": "21530115",
                    "business_unit": "B",
                         */
        });
        return jsonObjectRes;

    }


}
